package com.dindang.maintenance.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewTreeObserver;

import com.alibaba.android.arouter.launcher.ARouter;
import com.dindang.maintenance.R;
import com.dindang.maintenance.app.utils.TextTransformUtils;
import com.dindang.maintenance.mvp.contract.MaintainDetailsContract;
import com.dindang.maintenance.mvp.model.CommontCons;
import com.dindang.maintenance.mvp.model.entity.BaseResponse;
import com.dindang.maintenance.mvp.model.entity.Repair;
import com.dindang.maintenance.mvp.ui.adapter.custom.MaintainImageViewAdapter;
import com.dindang.maintenance.mvp.ui.adapter.custom.ProgressViewAdapter;
import com.dindang.maintenance.mvp.ui.widget.AddProgressDialog;
import com.dindang.maintenance.mvp.ui.widget.ScaleImageView;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.dialog.WaitDialog;
import com.longxi.gamer_base.model.MaintainDetailsEvent;
import com.longxi.gamer_base.utils.KeyBoardUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class MaintainDetailsPresenter extends BasePresenter<MaintainDetailsContract.Model, MaintainDetailsContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private List<String> mImgList = new ArrayList<>();
    private LinearLayoutManager mImageLayoutManager;
    private MaintainImageViewAdapter mImageAdapter;
    private int imageWidth = 0;
    private List<Repair.FlowDetail.FlowList> mProgressList = new ArrayList<>();
    private ProgressViewAdapter mProgressAdapter;
    private ScaleImageView mScaleImageView;

    private WaitDialog mWaitDialog;
    private Repair.FlowDetailParam mParam = new Repair.FlowDetailParam();
    private Repair.AddFlowParam mAddFlowParam;
    private List<String> mStateList = new ArrayList<>();// 通过这个给数据增加处理轨迹中标红的东西 详情请看原型 不服请找后台
    private String mState;
    private String mPhone;
    private MaintainDetailsEvent mMaintainDetailsEvent = new MaintainDetailsEvent();

    @Inject
    public MaintainDetailsPresenter(MaintainDetailsContract.Model model, MaintainDetailsContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        mWaitDialog = new WaitDialog(mRootView.getActivity());
        EventBus.getDefault().register(this);
        initAdapter();
        initListener();
        initScaleImageView();
        quertFlowDetail();
    }

    private void initScaleImageView() {
        mScaleImageView = new ScaleImageView(mRootView.getActivity());
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        mImageLayoutManager=new LinearLayoutManager(mRootView.getActivity());
        mImageAdapter = new MaintainImageViewAdapter(mImgList);//
        mImageLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);//横排
//        mRootView.getRvImage().addItemDecoration(new RecycleViewDivider(mRootView.getRvImage().getContext(), LinearLayoutManager.HORIZONTAL, 100, mRootView.getRvImage().getContext().getResources().getColor(R.color.white)));//增加间隔
        mRootView.getRvImage().setLayoutManager(mImageLayoutManager);
        mRootView.getRvImage().setAdapter(mImageAdapter);
        ViewTreeObserver vto = mRootView.getRvImage().getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                if(imageWidth == 0){
                    imageWidth = mRootView.getRvImage().getMeasuredWidth();
                    mImageAdapter.setImageWidth(imageWidth);
                }
                return true;
            }
        });

        mProgressAdapter = new ProgressViewAdapter(mProgressList);
        mRootView.getRvProgress().setAdapter(mProgressAdapter);
    }

    private void initListener() {
        mRootView.getIvToRight().setOnClickListener(v -> moveToPosition());
        mRootView.getTvSendOrder().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build("/maintenance/activity/SendOrderActivity").navigation();
            }
        });

        mRootView.getTvSendOrder().setOnClickListener(v -> {
            switch (mState) {
                case "1":// 待派单
                    ARouter.getInstance().build("/maintenance/activity/SendOrderActivity")
                            .withString("id", mRootView.getActivity().getIntent().getStringExtra("id")).navigation();
                    break;
                case "2":// 待接单
                    mAddFlowParam = new Repair.AddFlowParam(mRootView.getActivity().getIntent().getStringExtra("id"),
                            BaseAppConst.accountInfo.getCorpId(),
                            BaseAppConst.accountInfo.getCorpName(),
                            BaseAppConst.accountInfo.getCorpId(),
                            "2");
                    insertFlow();
                    break;
                case "3":
                    dialogProgress(R.string.maintenance_title_completion, "6");
                    break;
            }

        });

        mRootView.getIvPhone().setOnClickListener(v -> {
            toPlayPhone();
        });

        mRootView.getTvPlan().setOnClickListener(v -> {
            ARouter.getInstance().build("/maintenance/activity/PlanActivity")
                    .withString("id", mRootView.getActivity().getIntent().getStringExtra("id")).navigation();
        });

        /**
         * 追记用
         */
        mRootView.getTvProgress().setOnClickListener(v -> {
            dialogProgress(R.string.maintenance_title_progress_describe, "0");
        });

        /**
         * 暂停 撤销 继续 用
         */
        mRootView.getTvUndo().setOnClickListener(v -> {
            switch (mState) {
                case "1":
                    dialogProgress(R.string.maintenance_title_reback_reason, "9");
                    break;
                case "3":
                    dialogProgress(R.string.maintenance_title_suspension_reason, "4");
                    break;
                case "4":
                    mAddFlowParam = new Repair.AddFlowParam(mRootView.getActivity().getIntent().getStringExtra("id"),
                            BaseAppConst.accountInfo.getCorpId(),
                            BaseAppConst.accountInfo.getCorpName(),
                            BaseAppConst.accountInfo.getCorpId(),
                            "5");
                    insertFlow();
                    break;
            }
        });
    }

    private void moveToPosition() {
        //获取当前recycleView屏幕可见的第一项和最后一项的Position
        mRootView.getRvImage().smoothScrollToPosition(mImgList.size() - 1);
    }

    /**
     * 不知道是不是这个接口 查询流程详情
     */
    private void quertFlowDetail(){
        mWaitDialog.showWaitingDialog(ArmsUtils.getString(mApplication, R.string.data_load));
        mParam.id = mRootView.getActivity().getIntent().getStringExtra("id");
        mModel.quertFlowDetail(mParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {
            mWaitDialog.hideWaitingDialog();
        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<Repair.FlowDetail>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<Repair.FlowDetail> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                setData(response);
            }
        });
    }

    String[] states = CommontCons.states;
    private void setData(BaseResponse<Repair.FlowDetail> response) {
        mPhone = response.getData().repairsDetail.cApplytel;
        mRootView.getIvPhone().setVisibility(View.VISIBLE);

        mStateList.clear();
        mProgressList.clear();
        mImgList.clear();

        if(!response.isSuccess()){
            ArmsUtils.makeText(mApplication, response.getStatuMsg());
            return;
        }

        mState = response.getData().repairsDetail.cStatus;
        mRootView.getTvState().setText(states[TextTransformUtils.string2Int(mState)]);

        mRootView.getTvOrdernoValue().setText(response.getData().repairsDetail.cNumcard);
        if("1".equals(response.getData().repairsDetail.cApplyarea)){
            mRootView.getTvRepairAreaValue().setText("私有区域");
        }else if("2".equals(response.getData().repairsDetail.cApplyarea)){
            mRootView.getTvRepairAreaValue().setText("公共区域");
        }
        mRootView.getTvRepairManValue().setText(response.getData().repairsDetail.cApplyname);
        String cIdentity = "其他";
        switch (response.getData().repairsDetail.cIdentity) {
            case "1":
                cIdentity = "住户";
                break;
            case "2":
                cIdentity = "员工";
                break;
        }
        mRootView.getTvRepairManLabel().setText(cIdentity);
        if(response.getData().repairsDetail.cEndDate.isEmpty()){
            mRootView.getTvAppointmentTimeValue().setText(response.getData().repairsDetail.dAppointdate + " " + response.getData().repairsDetail.cStartDate);
        }else {
            mRootView.getTvAppointmentTimeValue().setText(response.getData().repairsDetail.dAppointdate + " " + response.getData().repairsDetail.cStartDate + "至" + response.getData().repairsDetail.cEndDate);
        }

        mRootView.getTvProjectNameValue().setText(response.getData().repairsDetail.cBuildingname);
//        mRootView.getTvPresentTimeValue().setText(TimeComparisonUtils.dateTString3(response.getData().repairsDetail.dCreatedate));
        mRootView.getTvRepairTimeValue().setText(response.getData().repairsDetail.dCreatedate);
        if(response.getData().repairsDetail.cErrtype!=null){
            if(TextTransformUtils.string2Int(response.getData().repairsDetail.cErrtype)<5&&TextTransformUtils.string2Int(response.getData().repairsDetail.cSubtype)<6){
                if(response.getData().repairsDetail.cErrtype.equals("1")){
                    mRootView.getTvRepairTypeValue().setText(CommontCons.err_type[TextTransformUtils.string2Int(response.getData().repairsDetail.cErrtype)]+"-"+CommontCons.sub_type1[TextTransformUtils.string2Int(response.getData().repairsDetail.cSubtype)]);
                }else if(response.getData().repairsDetail.cErrtype.equals("2")){
                    mRootView.getTvRepairTypeValue().setText(CommontCons.err_type[TextTransformUtils.string2Int(response.getData().repairsDetail.cErrtype)]+"-"+CommontCons.sub_type2[TextTransformUtils.string2Int(response.getData().repairsDetail.cSubtype)]);
                }else if(response.getData().repairsDetail.cErrtype.equals("3")){
                    mRootView.getTvRepairTypeValue().setText(CommontCons.err_type[TextTransformUtils.string2Int(response.getData().repairsDetail.cErrtype)]+"-"+CommontCons.sub_type3[TextTransformUtils.string2Int(response.getData().repairsDetail.cSubtype)]);
                }else if(response.getData().repairsDetail.cErrtype.equals("4")){
                    mRootView.getTvRepairTypeValue().setText(CommontCons.err_type[TextTransformUtils.string2Int(response.getData().repairsDetail.cErrtype)]+"-"+CommontCons.sub_type4[TextTransformUtils.string2Int(response.getData().repairsDetail.cSubtype)]);
                }else {
                    mRootView.getTvRepairTypeValue().setText(CommontCons.err_type[TextTransformUtils.string2Int(response.getData().repairsDetail.cErrtype)]+"-"+CommontCons.sub_type4[TextTransformUtils.string2Int(response.getData().repairsDetail.cSubtype)]);
                }
            }
        }
        
        mRootView.getTvRepairTypeValue().setText(response.getData().repairsDetail.cErrtype + "-" + response.getData().repairsDetail.cSubtype);
        mRootView.getTvFaultTypesValue().setText(response.getData().repairsDetail.cAddress);
        mRootView.getTvFaultDescriptionValue().setText(response.getData().repairsDetail.cContent);

        String[] imgs = response.getData().repairsDetail.cApplyimage.split(",");
        for (String img : imgs) {
            if(!"".equals(img)){
                mImgList.add(img);
            }
        }

        if(mImgList.size() == 0){
            mRootView.getRvImage().setVisibility(View.GONE);
            mRootView.getIvToRight().setVisibility(View.GONE);
        }else if(mImgList.size() <= 4 && mImgList.size() > 0){
            mRootView.getRvImage().setVisibility(View.VISIBLE);
            mRootView.getIvToRight().setVisibility(View.GONE);
        }else{
            mRootView.getRvImage().setVisibility(View.VISIBLE);
            mRootView.getIvToRight().setVisibility(View.VISIBLE);
        }

        mImageAdapter.setListener(new MaintainImageViewAdapter.OnClickListener() {
            @Override
            public void onClick(int position) {
                mScaleImageView.setUrls(mImgList, position);
                mScaleImageView.create();
            }
        });
        mImageAdapter.notifyDataSetChanged();

        response.getData().flowList.add(new Repair.FlowDetail.FlowList(response.getData().repairsDetail.dCreatedate,
                response.getData().repairsDetail.cCreator,
                response.getData().repairsDetail.dAppointdate + " " + response.getData().repairsDetail.cStartDate + "至" + response.getData().repairsDetail.cEndDate,
                "100"));

        for (Repair.FlowDetail.FlowList flowList : response.getData().flowList) {
            mStateList.add(flowList.c_status);
        }

        addRedFlow(response.getData().flowList);
        showBottomBtn();

        mProgressList.addAll(response.getData().flowList);
        for(Repair.FlowDetail.FlowList flowList : response.getData().flowList){
            if(null != flowList.d_appoint_date){
                mRootView.getTvPresentTimeValue().setText(flowList.d_appoint_date);
            }
        }
        mProgressAdapter.notifyDataSetChanged();
    }

    /**
     * 为记录添加一条数据
     * @param flowList
     */
    private void addRedFlow(List<Repair.FlowDetail.FlowList> flowList) {
//        (0.追记1.派单 2.接单 3.重新派单->2 4.暂停5.继续6.完成7.已回访8.评价9.撤销注：追记和重新派单为非主业务流程)
//        状态(1:待派单 2:待接单 3:待完成4:暂停中5:待回访6:已回访9已撤销)
        switch (mState) {
            case "1":// 派单
            case "3":// 重新派单
                if(mStateList.contains("1") || mStateList.contains("3")){
                    flowList.add(0, new Repair.FlowDetail.FlowList("99", "待接单"));
                }else{
                    flowList.add(0, new Repair.FlowDetail.FlowList("99","待派单"));
                }
                break;
            case "2":// 接单
                if(mStateList.contains("2")){
                    flowList.add(0, new Repair.FlowDetail.FlowList("99","待接单"));
                }else{
                    flowList.add(0, new Repair.FlowDetail.FlowList("99","待完成"));
                }
                break;
            case "4":// 暂停
            case "5":// 继续
                flowList.add(0, new Repair.FlowDetail.FlowList("99","待回访"));
                break;
            case "6":// 完成
                flowList.add(0, new Repair.FlowDetail.FlowList("99","已回访"));
                break;
        }
    }

    /**
     * 底部按钮显示
     */
    public void showBottomBtn() {
        mRootView.getConstraintlayout().setVisibility(View.GONE);
        switch (mState) {
            case "1":
                mRootView.getConstraintlayout().setVisibility(View.VISIBLE);
                mRootView.getTvSendOrder().setVisibility(View.VISIBLE);
                mRootView.getTvSendOrder().setText("派单");
                mRootView.getTvPlan().setVisibility(View.GONE);
                mRootView.getTvProgress().setVisibility(View.VISIBLE);
                mRootView.getTvProgress().setText("追记");
                mRootView.getTvUndo().setVisibility(View.VISIBLE);
                mRootView.getTvUndo().setText("撤销");
                break;
            case "2":
                mRootView.getConstraintlayout().setVisibility(View.VISIBLE);
                mRootView.getTvSendOrder().setVisibility(View.VISIBLE);
                mRootView.getTvSendOrder().setText("立即接单");
                mRootView.getTvPlan().setVisibility(View.GONE);
                mRootView.getTvProgress().setVisibility(View.GONE);
                mRootView.getTvUndo().setVisibility(View.GONE);
                break;
            case "3":
                mRootView.getConstraintlayout().setVisibility(View.VISIBLE);
                mRootView.getTvSendOrder().setVisibility(View.VISIBLE);
                mRootView.getTvSendOrder().setText("完成");
                mRootView.getTvPlan().setVisibility(View.VISIBLE);
                mRootView.getTvPlan().setText("方案");
                mRootView.getTvProgress().setVisibility(View.VISIBLE);
                mRootView.getTvProgress().setText("追记");
                mRootView.getTvUndo().setVisibility(View.VISIBLE);
                mRootView.getTvUndo().setText("暂停");
                break;
            case "4":
                mRootView.getConstraintlayout().setVisibility(View.VISIBLE);
                mRootView.getTvSendOrder().setVisibility(View.GONE);
                mRootView.getTvPlan().setVisibility(View.GONE);
                mRootView.getTvProgress().setVisibility(View.GONE);
                mRootView.getTvUndo().setVisibility(View.VISIBLE);
                mRootView.getTvUndo().setText("继续");
                break;
            case "5":
                mRootView.getTvSendOrder().setVisibility(View.GONE);
                mRootView.getTvPlan().setVisibility(View.GONE);
                mRootView.getTvProgress().setVisibility(View.GONE);
                mRootView.getTvUndo().setVisibility(View.GONE);
                break;
            case "6":
                mRootView.getTvSendOrder().setVisibility(View.GONE);
                mRootView.getTvPlan().setVisibility(View.GONE);
                mRootView.getTvProgress().setVisibility(View.GONE);
                mRootView.getTvUndo().setVisibility(View.GONE);
                break;
            default:
                mRootView.getTvSendOrder().setVisibility(View.GONE);
                mRootView.getTvPlan().setVisibility(View.GONE);
                mRootView.getTvProgress().setVisibility(View.GONE);
                mRootView.getTvUndo().setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 打电话
     */
    public void toPlayPhone() {
        if("".equals(mPhone)){
            ArmsUtils.makeText(mApplication, "当前业主手机号不存在");
            return;
        }
        Intent dialIntent =  new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" +  mPhone));//跳转到拨号界面，同时传递电话号码
        mRootView.getActivity().startActivity(dialIntent);
    }

    private void insertFlow(){
        mWaitDialog.showWaitingDialog(ArmsUtils.getString(mApplication, R.string.data_load));
        mModel.insertFlow(mAddFlowParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(0, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {
            mWaitDialog.hideWaitingDialog();
        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                ArmsUtils.makeText(mApplication, response.getStatuMsg());
                if(!response.isSuccess()){
                    return;
                }
                EventBus.getDefault().post(mMaintainDetailsEvent);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mProgressAdapter = null;
        this.mProgressList = null;
        this.mImageLayoutManager = null;
        this.mImgList = null;
        this.mImageAdapter = null;
        this.mScaleImageView = null;

        this.mParam = null;

        this.mStateList = null;
        this.mMaintainDetailsEvent = null;

        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void MaintainDetailsRefresh(MaintainDetailsEvent maintainDetailsEvent){
        quertFlowDetail();
    }

    private AddProgressDialog.Builder addProgressDialog;
    /**
     * 追记弹框
     */
    private void dialogProgress(int title, String state){
        if(addProgressDialog != null){
            addProgressDialog.show();
        }else{
            addProgressDialog = new AddProgressDialog.Builder(mRootView.getActivity());
            addProgressDialog
            .setListener(new AddProgressDialog.OnClickListener() {
                @Override
                public void onClick(String describe, String cStatus) {
                    mAddFlowParam = new Repair.AddFlowParam(mRootView.getActivity().getIntent().getStringExtra("id"),
                            BaseAppConst.accountInfo.getCorpId(),
                            BaseAppConst.accountInfo.getCorpName(),
                            BaseAppConst.accountInfo.getCorpId(),
                            cStatus);
                    mAddFlowParam.cRemark = describe;
                    addProgressDialog.dismiss();
                    insertFlow();
                }

                @Override
                public void onHideKeyBorder() {
                    hideKeyBorder();
                }
            })
            .create()
            .show();
        }
        addProgressDialog.setTitle2(ArmsUtils.getString(mApplication, title), state);
        addProgressDialog.clear();
    }

    private void hideKeyBorder(){
        KeyBoardUtil.hideKeyBoard(mRootView.getActivity());
    }

}
